<template>
  <div>
    <Row>
      <Col :span="12">
      <div class="wrap-box">
        <div class="p-home-title">用户信息</div>
        <div class="p-background">
          <div class="p-home-content" style="padding-top: 43px;height: 252px;">
            <Form :model="formLabelAlign">
              <FormItem label="用户名">
                <Input :disabled="true" v-model="this.userName" placeholder="请输入用户名"></Input>
              </FormItem>
              <FormItem label="注册时间">
                <Input :disabled="true" v-model="this.registerData" placeholder="请输入注册时间"></Input>
              </FormItem>
            </Form>
          </div>
        </div>
      </div>
      </Col>
      <Col :span="12">
      <div class="wrap-box" style="margin-left: 20px">
        <div class="p-home-title">用户头像</div>
        <div class="p-background">
          <div class="p-home-content" style="margin-top: 35px">
            <div class="demo-upload-list" v-for="item in uploadList">
              <template v-if="item.status === 'finished'">
                <img :src="item.url">
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline"
                        @click.native="handleView(item.url)"></Icon>
                  <Icon type="ios-trash-outline"
                        @click.native="handleRemove(item)"></Icon>
                </div>
              </template>
              <template v-else>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
              </template>
            </div>
            <Upload
              v-show="uploadList.length == 0"
              ref="upload"
              :show-upload-list="false"
              :default-file-list="defaultList"
              :format="['jpg','jpeg','png']"
              :max-size="1024 * 100"
              multiple
              type="drag"
              :action='imgUrl'
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              :on-success="handleAvatarSuccess"
              :before-upload="handleBeforeUpload"
              style="display: inline-block;width:160px;"
            >
              <div style="width: 160px;height:160px;line-height: 160px;">
                <Icon type="camera" size="20"></Icon>
              </div>
            </Upload>
            <Modal title="图片预览" v-model="visible" :loading="true">
              <img :src="imgName" v-if="visible" style="width: 100%">
              <div slot="footer"></div>
            </Modal>
          </div>
        </div>
      </div>
      </Col>
    </Row>

    <Row style="margin-top: 20px">
      <Col :span="12">
      <div class="wrap-box">
        <div class="p-home-title">密码修改</div>
        <div class="p-background">
          <div class="p-home-content" style="padding-top: 16px;height: 350px;">
            <Form :model="formLabelAlign" :rules="formLabelAlignRules" ref="formLabelAlign">
              <FormItem label="旧密码" prop="password">
                <Input type="password" v-model="formLabelAlign.password" placeholder="请输入旧密码"></Input>
              </FormItem>
              <FormItem label="新密码" prop="newPassword">
                <Input type="password" v-model="formLabelAlign.newPassword" placeholder="请输入新密码"></Input>
              </FormItem>
              <FormItem label="密码确认" prop="affirmPassword">
                <Input type="password" v-model="formLabelAlign.affirmPassword" placeholder="再次输入密码"></Input>
              </FormItem>
            </Form>
            <div style="text-align: center;">
              <Button type="primary" @click.native="affirm('formLabelAlign')">确认修改</Button>
            </div>
          </div>
        </div>
      </div>
      </Col>
    </Row>
  </div>
</template>
<script type="text/ecmascript-6">
  import Vue from 'vue'
  import {SERVICE_URLS} from "../../libs/service.url";


  export default {
    data() {
      return {
        uploadList: [],
        defaultList: [],
        visible: false,
        imgName: '',
        imgUrl: SERVICE_URLS.user.imgUrl.path,
        userName: '',
        userId: "",
        requestImgUrl: '',
        registerData: '',
        imgUp: "", // 修改的头像
        formLabelAlign: {
          password: '',
          newPassword: '',
          affirmPassword: ''
        },
        formLabelAlignRules: {
          password: [
            {required: true, message: '输入旧密码', trigger: 'blur'},
          ],
          newPassword: [
            {required: true, message: '请输入新密码', trigger: 'blur'},
            {min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur'}
          ],
          affirmPassword: [
            {required: true, message: '再次输入密码', trigger: 'blur'},
            {min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur'}
          ]
        },
      }
    },
    created() {
      if (this.currentUser) {
        this.userName = this.currentUser.loginName;
        this.registerData = this.currentUser.createTime;
        this.userId = this.currentUser.id;
      }
      if (this.currentUser.headPhotoUrl != null && this.currentUser.headPhotoUrl != "") {
        this.imageUrl = this.currentUser.imgHeadUrl + this.currentUser.headPhotoUrl;
      }
//      this.getUserInfo(this.userId);
    },
    computed: {
      currentUser() {
        return this.$store.getters.currentUser
      }
    },
    updated() {
      this.uploadList = this.$refs.upload.fileList;
    },
    mounted() {
      this.uploadList = this.$refs.upload.fileList;
    },
    methods: {
      getUserInfo(userId) {
        Vue.submit(this, {
          url: SERVICE_URLS.user.userinfo,
          params: {
            id: userId,
          },
          callback: (data) => {
            this.userName = data.realName;
            if (data.headPhotoUrl) {
              this.defaultList.push({
                'name': this.currentUser.headPhotoUrl,
                'url': this.currentUser.imgHeadUrl + this.currentUser.headPhotoUrl
              });
            } else {
              this.defaultList.push({
                'name': '',
                'url': "http://yilancmp.oss-cn-beijing.aliyuncs.com/x8bOuPvuQQG4vAU.jpg?Expires=1844156021&OSSAccessKeyId=LTAIsgCBfpOosVuh&Signature=1VF27y6PoebPYMze%2FPKScH6eQjg%3D"
              });
            }
          }
        })
      },
      handleView(name) {
        this.imgName = name;
        this.visible = true;
      },
      handleRemove(file) {
        const fileList = this.$refs.upload.fileList;
        this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
      },
      handleAvatarSuccess(res, file) {
        this.imgUp = file.response.result;
        file.url = this.currentUser.imgHeadUrl + file.response.result
        this.confirmImgUp();
      },
      handleMaxSize(file) {
        this.$Notice.warning({
          title: 'Exceeding file size limit',
          desc: 'File  ' + file.name + ' is too large, no more than 2M.'
        });
      },
      handleFormatError(file) {
        this.$Notice.warning({
          title: 'The file format is incorrect',
          desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
        });
      },
      handleBeforeUpload() {
        const check = this.uploadList.length < 5;
        if (!check) {
          this.$Notice.warning({
            title: 'Up to five pictures can be uploaded.'
          });
        }
        return check;
      },
      confirmImgUp() {
        Vue.submit(this, {
          url: SERVICE_URLS.user.headPortraitModification,
          data: {
            id: this.userId,
            headPhotoUrl: this.imgUp
          },
          callback: () => {
            Vue.submit(this, {
              url: SERVICE_URLS.user.userinfo,
              params: {
                id: this.userId,
              },
              callback: (data) => {
                this.currentUser.headPhotoUrl = data.headPhotoUrl;
                localStorage.setItem('currentUser', JSON.stringify(this.currentUser));
              }
            });
            this.$Message.success('操作成功!');
          }
        })
      },
      // 确认修改
      affirm(formName) {
        const self = this;
        this.checkColumnName(self.formLabelAlign.password).then(() => {
          if (self.formLabelAlign.newPassword == self.formLabelAlign.affirmPassword) {
            Vue.submit(self, {
              formName: formName,  // 表单验证
              url: SERVICE_URLS.user.passwordModification,
              data: {
                id: self.userId,
                password: sha512(self.formLabelAlign.affirmPassword)
              },
              callback: () => {
                self.$Message.success('操作成功!')
              }, err(err, data) {
                self.$Message.success('`${data.message}`');
              }
            })
          } else {
            self.$Message.info('两次密码不一致!')
          }
        });
      },
      // 验证密码
      checkColumnName(password) {
        const self = this;
        return new Promise(function (resolve, reject) {
          Vue.submit(self, {
            url: SERVICE_URLS.user.userPassword,
            data: {
              id: self.userId,
              password: sha512(password)
            },
            callback: (data) => {
              resolve()  // 成功
            }, error: (data) => {
              self.$Message.error("原密码错误！")
            }
          })
        })

      }
    }
  }
</script>
<style scoped lang="scss">
  .p-home-title {
    background: #409EFF;
    color: #fff;
    height: 38px;
    line-height: 38px;
    text-align: center;
    border-radius: 9px 9px 0 0;
  }

  .p-home-content {
    height: 215px;
    background: #fff;
    width: 53%;
    margin: auto;
  }

  .p-background {
    background: #fff;
    border: 1px solid #dfe2e6;
  }

  .demo-upload-list {
    display: inline-block;
    width: 160px;
    height: 160px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
    margin-right: 4px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }

  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, .6);
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }

  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 70px 2px;
  }
</style>
